<template>
	<div class="zuZhiJiaGou center align-start fWrap">
		<div class="right bfff left-bumen">
			<div class="title">
				<el-button type="primary" plain @click="setShowMore" v-auth="['system:sysUser:save']">
					<div class="center">
						<i class="iconfont f14 mr15">&#xe651;</i>
						新增部门
					</div>
				</el-button>
			</div>
			<el-tree
				class="el-tree elTreeicon"
				ref="treeRef"
				:data="dataList"
				default-expand-all
				node-key="id"
				highlight-current
				:props="defaultProps"
				:default-expanded-keys="[9, 10]"
				:expand-on-click-node="false"
				@node-click="tabList"
			>
				<template #default="{ node, data }">
					<div class="el-tree-item">
						<span class="f14 c333 treeRefSpan"
							><el-tooltip effect="light" :content="node.label" placement="top">
								{{ node.label }}
							</el-tooltip>
						</span>
						<el-button
							class="el-button"
							type="primary"
							link
							:icon="Edit"
							v-auth="['system:sysDept:info', 'system:sysDept:edit']"
							@click.stop="editTree(data)"
						></el-button>
						<el-button
							class="el-button"
							type="danger"
							link
							:icon="Delete"
							v-auth="['system:sysUser:delete', 'system:sysDept:delete']"
							@click.stop="delTree(data)"
						></el-button>
					</div>
				</template>
			</el-tree>
		</div>
		<div class="nav-dis" @click="drawer = true">部门</div>
		<el-drawer v-model="drawer" size="70%" :with-header="false">
			<div class="title">
				<el-button type="primary" plain @click="setShowMore" v-auth="['system:sysDept:save']">
					<div class="center">
						<i class="iconfont f14 mr15">&#xe651;</i>
						新增部门
					</div>
				</el-button>
			</div>
			<el-tree
				class="el-tree elTreeicon"
				ref="treeRef"
				:data="dataList"
				default-expand-all
				node-key="id"
				highlight-current
				:props="defaultProps"
				:default-expanded-keys="[9, 10]"
				:expand-on-click-node="false"
				@node-click="tabList"
			>
				<template #default="{ node, data }">
					<div class="el-tree-item">
						<span class="f14 c333 treeRefSpan"> {{ node.label }}</span>
						<el-button
							class="el-button"
							type="primary"
							link
							:icon="Edit"
							v-auth="['system:sysDept:info', 'system:sysDept:edit']"
							@click.stop="editTree(data)"
						></el-button>
						<el-button
							class="el-button"
							type="danger"
							link
							:icon="Delete"
							v-auth="['system:sysUser:delete', 'system:sysDept:delete']"
							@click.stop="delTree(data)"
						></el-button>
					</div>
				</template>
			</el-tree>
		</el-drawer>

		<div class="left flex">
			<div class="bfff left-bottom">
				<div class="center flex-start table-head3 fWrap">
					<div class="c666 f14">用户名：</div>
					<div>
						<el-input
							type="text"
							placeholder="请输入用户名"
							v-model="onSearchText"
							@keyup.enter.native="onSearch"
						/>
					</div>
					<div class="box-button-top">
						<el-button class="primary" type="primary" @click="onSearch">搜索</el-button>
						<el-button type="primary" plain @click="resetting">重置</el-button>
					</div>
				</div>
				<div class="center flex-start fWrap table-head">
					<el-button class="primary" type="primary" @click="addUser" v-auth="['system:sysUser:save']">
						+新增成员
					</el-button>
					<el-button
						class="danger"
						@click="efficacy('num')"
						type="success"
						plain
						v-auth="['system:sysUser:setStatus']"
					>
						置为生效
					</el-button>
					<el-button
						class="danger"
						@click="efficacy()"
						type="warning"
						plain
						v-auth="['system:sysUser:setStatus']"
					>
						置为失效
					</el-button>
				</div>
				<div class="center table-head2">
					<div class="f14 choice-num flex ctheme">已选：{{ tableLis.length }}</div>
				</div>
				<div class="table-scrol">
					<div class="table">
						<el-table
							@select="selectClick"
							:data="departmentList"
							@select-all="selectAll"
							style="width: 100%"
						>
							<el-table-column align="center" type="selection" min-width="60" />
							<el-table-column
								align="center"
								prop="realName"
								label="姓名"
								show-overflow-tooltip
								min-width="150"
							/>
							<el-table-column
								align="center"
								prop="loginName"
								label="登录名"
								show-overflow-tooltip
								min-width="150"
							/>
							<el-table-column
								align="center"
								prop="status"
								label="状态"
								show-overflow-tooltip
								min-width="100"
							>
								<template #default="{ row }">
									<el-tag
										type="success"
										class="tagButton"
										v-if="row.status == 1"
										@click="onEnable(row, 2)"
										>生效</el-tag
									>
									<el-tag type="warning" class="tagButton" v-else @click="onEnable(row, 1)"
										>未生效</el-tag
									>
								</template>
							</el-table-column>
							<el-table-column
								align="center"
								prop="deptName"
								label="部门"
								show-overflow-tooltip
								min-width="200"
							/>
							<el-table-column
								align="center"
								prop="phone"
								label="联系方式"
								show-overflow-tooltip
								min-width="200"
							/>
							<el-table-column align="center" label="操作" min-width="200">
								<template #default="{ row }">
									<div class="table-color">
										<el-button
											:icon="EditPen"
											v-auth="['system:sysUser:info', 'system:sysUser:edit']"
											@click="editTable(row)"
											title="编辑"
										></el-button>
										<el-button
											:icon="Key"
											@click="keyTable(row)"
											v-auth="['system:sysUser:edit']"
											title="重置密码"
										></el-button>
										<el-button
											:icon="Delete"
											@click="delTable(row)"
											v-auth="['system:sysUser:delete', 'system:sysDept:delete']"
											title="删除"
										></el-button>
									</div>
								</template>
							</el-table-column>
							<template #empty>
								<el-empty description="暂无数据" />
							</template>
						</el-table>
					</div>
				</div>
				<div class="bfff pagination-class">
					<v-pagination
						:total="total"
						v-model:size="pageSize"
						v-model:page="current"
						@pagination="fetchList"
						@paginations="fetchList"
					></v-pagination>
				</div>
			</div>
		</div>
		<!-- 新增成员信息 -->
		<el-dialog
			class="cheng-dialog"
			v-model="visible"
			:show-close="false"
			:close-on-click-modal="false"
			destroy-on-close
			width="800px"
		>
			<template #header="{ close, titleId, titleClass }">
				<div class="dialog-header center btheme cfff">
					<img src="@/assets/image/houTai/xinc.png" alt="" />
					<div class="flex f16">{{ title }}</div>
					<el-icon class="pointer" size="20" color="#fff" @click="quXiao">
						<Close />
					</el-icon>
				</div>
			</template>
			<div class="dialog-content">
				<el-form ref="ruleFormRef" :model="form" :rules="rules" class="demo-ruleForm" label-width="100px">
					<div class="center">
						<div class="flex">
							<el-form-item label="姓名" prop="name">
								<el-input class="name" v-model="form.name" placeholder="请输入姓名" />
							</el-form-item>
						</div>
						<div class="flex">
							<el-form-item label="昵称" prop="nickname">
								<el-input class="name" v-model="form.nickname" placeholder="请输入昵称" />
							</el-form-item>
						</div>
					</div>
					<div class="center">
						<div class="flex">
							<el-form-item label="性别" prop="gender">
								<el-radio-group v-model="form.gender">
									<el-radio :label="'m'">男</el-radio>
									<el-radio :label="'f'">女</el-radio>
								</el-radio-group>
							</el-form-item>
						</div>
					</div>
					<div class="center">
						<div class="flex">
							<el-form-item label="状态" prop="status">
								<el-switch
									v-model="form.status"
									active-text="生效"
									:active-value="activeValue"
									:inactive-value="inactiveValue"
								/>
							</el-form-item>
						</div>
					</div>
					<div class="center">
						<div class="flex">
							<el-form-item label="邮件地址" prop="email">
								<el-input class="name" v-model="form.email" placeholder="请输入邮件地址" />
							</el-form-item>
						</div>
					</div>
					<el-form-item label="角色" prop="role">
						<el-select multiple v-model="form.role" placeholder="请选择角色">
							<el-option v-for="item in part" :key="item.id" :label="item.name" :value="item.id" />
						</el-select>
					</el-form-item>
					<el-form-item label="部门" prop="deptId">
						<el-cascader
							clearable
							v-model="form.deptId"
							:show-all-levels="false"
							props.checkStrictly="true"
							placeholder="请选择部门"
							:options="dataList"
							:props="{
								value: 'id',
								label: 'name',
								children: 'children',
								checkStrictly: true,
							}"
							@change="chooseJqfl"
						/>
					</el-form-item>
					<el-form-item label="手机号码" prop="phone">
						<el-input class="name" v-model="form.phone" placeholder="请输入手机号码" />
					</el-form-item>
					<el-form-item label="办公电话" prop="officePhone">
						<el-input class="name" v-model="form.officePhone" placeholder="请输入办公电话" />
					</el-form-item>
					<div class="center">
						<div class="flex">
							<el-form-item label="登录名" prop="loginName">
								<template #label>
									<span>登录名</span>
									<el-tooltip
										class="box-item"
										effect="dark"
										content="登录名由4-10位数字和字母组成"
										placement="top"
										:offset="0"
									>
										<el-icon class="label-icon"><InfoFilled /></el-icon>
									</el-tooltip>
								</template>
								<template #default>
									<el-input
										class="name"
										v-model="form.loginName"
										placeholder="请输入登录名"
										:disabled="!dengUser"
								/></template>
							</el-form-item>
						</div>
						<div class="flex" v-if="passwordIf">
							<el-form-item label="密码" prop="password">
								<template #label>
									<span>密码</span>
									<el-tooltip
										class="box-item"
										effect="dark"
										content="密码由5-16位数字、大小写字母组成"
										placement="top"
										:offset="0"
									>
										<el-icon class="label-icon"><InfoFilled /></el-icon>
									</el-tooltip>
								</template>
								<template #default>
									<el-input
										type="password"
										class="name"
										v-model="form.password"
										show-password
										placeholder="请输入密码"
									/>
								</template>
							</el-form-item>
						</div>
					</div>
				</el-form>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="quXiao">取消</el-button>
					<el-button type="primary" @click="submitForm(ruleFormRef)"> 确定 </el-button>
				</div>
			</template>
		</el-dialog>
		<el-dialog
			class="cheng-dialog"
			v-model="visibles"
			:show-close="false"
			:before-close="closeDepartment"
			:close-on-click-modal="false"
			destroy-on-close
			width="800px"
		>
			<template #header="{ close, titleId, titleClass }">
				<div class="dialog-header center btheme cfff">
					<img src="@/assets/image/houTai/xinc.png" alt="" />
					<div class="flex f16 fbold">{{ departmentTitle }}</div>
					<el-icon class="pointer" size="20" color="#fff" @click="closeDepartment">
						<Close />
					</el-icon>
				</div>
			</template>
			<el-form ref="ruleFormRefs" :model="department" :rules="ruless" label-width="100px">
				<el-form-item label="名称" prop="name">
					<el-input v-model="department.name" placeholder="请输入名称" maxlength="20" show-word-limit />
				</el-form-item>
				<el-form-item label="上级部门" prop="superior">
					<el-cascader
						clearable
						v-model="department.superior"
						:show-all-levels="false"
						:options="dataList"
						:props="{
							value: 'id',
							label: 'name',
							children: 'children',
							checkStrictly: true,
						}"
						@change="chooseJqfls"
					/>
				</el-form-item>
				<el-form-item label="备注" prop="notes">
					<el-input type="textarea" :rows="4" v-model="department.notes" maxlength="200" show-word-limit />
				</el-form-item>
				<el-form-item> </el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="closeDepartment">取消</el-button>
					<el-button type="primary" @click="submitForms(ruleFormRefs)"> 确定 </el-button>
				</div>
			</template>
		</el-dialog>
		<el-dialog
			class="cheng-dialog"
			v-model="visiblesKey"
			:show-close="false"
			:close-on-click-modal="false"
			destroy-on-close
			width="800px"
		>
			<template #header="{ close, titleId, titleClass }">
				<div class="dialog-header center btheme cfff">
					<img src="@/assets/image/houTai/xinc.png" alt="" />
					<div class="flex f16">修改密码</div>
					<el-icon class="pointer" size="20" color="#fff" @click="wordClone">
						<Close />
					</el-icon>
				</div>
			</template>
			<el-form ref="ruleFormRefKey" :model="formKey" :rules="rulesKey" label-width="100px">
				<el-form-item label="登录名" prop="loginName" v-if="userInfo.loginName == 'admin'">
					<el-input v-model="formKey.loginName" placeholder="请输入登录名" />
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<template #label>
						<span>密码</span>
						<el-tooltip
							class="box-item"
							effect="dark"
							content="密码由5-16位数字、大小写字母组成"
							placement="top"
							:offset="0"
						>
							<el-icon class="label-icon"><InfoFilled /></el-icon>
						</el-tooltip>
					</template>
					<template #default>
						<el-input
							v-model="formKey.password"
							type="password"
							show-password
							clearable
							placeholder="请输入密码"
						/>
					</template>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="wordClone">取消</el-button>
					<el-button type="primary" @click="submitFormsKey(ruleFormRefKey)"> 确定 </el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import { nextTick } from "vue"
import { Search, RefreshRight, EditPen, Delete, Key, Edit } from "@element-plus/icons-vue"
import { getAxios } from "/axios"
import { ElMessage, ElMessageBox } from "element-plus"
import md5 from "js-md5"
const { proxy } = getCurrentInstance()
const ruleFormRef = ref()
const drawer = ref(false)
const route = useRoute()
const router = useRouter()
// 新增成员信息
const visible = ref(false)
const userInfo = ref({})
const visiblesKey = ref(false)
const popoverVisible = ref([])
const inactiveValue = ref(2)
const activeValue = ref(1)
const dataList = ref([]) //部门列表
const departmentList = ref([]) //列表
// const isPostId = ref(true)
const onSearchText = ref("")
const departmentTitle = ref("")
const parentId = ref("")
const userId = ref("")
//新增部门
const visibles = ref(false)
const setShowMore = () => {
	fabu.value = false
	departmentTitle.value = "新增部门"
	visibles.value = !visibles.value
	department.superior = dataId.value
	if (ruless.superior.length != 1) {
		ruless.superior = [{ required: true, message: "请选择上级部门", trigger: "change" }]
	}
}
const dengUser = ref(true)
const passwordIf = ref(true)
const department = reactive({
	name: "", //名称
	superior: "", //上级部门
	notes: "", //备注
})
const total = ref(0)
const current = ref(1)
const formKey = reactive({
	password: "",
	loginName: "",
})
const dataId = ref("")
const defaultProps = reactive({
	children: "children",
	label: "name",
})
//角色
const pageSize = ref(10)
const part = ref([])
const form = reactive({
	name: "", //姓名
	nickname: "", //昵称
	status: 1, //状态
	gender: "", //性别
	email: "", //邮箱
	deptId: "", //部门
	role: [], //角色
	phone: "", //手机号
	officePhone: "", //办公电话
	postId: "", //所在岗位
	loginName: "", //登录名
	password: "", //密码
})
const selectAll = row => {
	tableLis.value = row
}
//选中
const tableLis = ref([])
const ruleFormRefKey = ref()
const options = ref([])
let checkPhone = (rule, value, callback) => {
	let reg = /^1[345789]\d{9}$/
	if (!reg.test(value)) {
		callback(new Error("请输入11位手机号"))
	} else {
		callback()
	}
}
const rules = reactive({
	name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
	gender: [{ required: true, message: "请选择性别", trigger: "change" }],
	password: [{ required: true, validator: passwordValidator, trigger: "blur" }],
	deptId: [{ required: true, message: "请选择部门", trigger: "change" }],
	role: [{ required: true, message: "请选择角色", trigger: "change" }],
	loginName: [{ required: true, validator: checkData, trigger: "blur" }],
	phone: [
		{ required: true, message: "请输入联系方式", trigger: "blur" },
		{ type: "number", validator: checkPhone, message: "请输入11位有效手机号", trigger: "blur" },
	],
	officePhone: [
		{
			pattern: /^[0-9]*$/,
			message: "办公电话只能为数字",
			trigger: "blur",
		},
	],
	email: [
		{
			pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
			message: "请输入正确的邮箱地址",
			trigger: "blur",
		},
	],
})
const ruless = reactive({
	name: [{ required: true, message: "请输入名称", trigger: "blur" }],
	superior: [{ required: true, message: "请选择上级部门", trigger: "change" }],
})
const rulesKey = reactive({
	password: [{ required: true, validator: passwordValidator, trigger: "blur" }],
})
function checkData(rule, value, callback) {
	let r1 = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{4,10}$/
	let valueList = value.split("")
	if (value) {
		if (valueList.length < 4 || valueList.length > 10) {
			callback(new Error("请输入4~10位的登录名"))
		}
		if (!r1.test(value)) {
			callback(new Error("请输入正确的用户名"))
		} else {
			callback()
		}
	} else {
		callback(new Error("请输入用户名"))
	}
}
function passwordValidator(rule, value, callback) {
	let count = 0
	let isNumber = /[0-9]/
	let isUpperLetter = /[A-Z]/
	let isLowerLetter = /[a-z]/
	let valueList = value.split("")
	let obj = {}
	for (let i = 0; i < value.length; i++) {
		if (obj[value[i]]) {
			obj[value[i]] += 1
		} else {
			obj[value[i]] = 0
		}
	}
	let objList = Object.values(obj)
	let objListIf = false
	objList.forEach(item => {
		if (item >= 3) {
			objListIf = true
		}
	})
	if (value) {
		if (valueList.length < 5 || valueList.length > 16) {
			callback(new Error("请输入5~16位的密码"))
		}
		if (objListIf) {
			callback(new Error("密码不能由3位连续字符组成"))
		}
		if (isNumber.test(value)) {
			count++
		}

		if (isUpperLetter.test(value)) {
			count++
		}

		if (isLowerLetter.test(value)) {
			count++
		}
		if (count == 3) {
			callback()
		} else {
			callback(new Error("密码由大小写字母和数字组成"))
		}
	} else {
		callback(new Error("请输入密码"))
	}
}
async function list() {
	const user = await postAxios(`/refreshToken`)
	window.localStorage.setItem("refreshToken", user.refreshToken || "")
	window.localStorage.setItem("token", user.token || "")
	//个人信息
	if (localStorage.getItem("userInfo")) {
		userInfo.value = JSON.parse(localStorage.getItem("userInfo"))
	} else {
		const user = await getAxios("/system/sysUser/selectById")
		if (user) {
			userInfo.value = user
		}
	}
	dataList.value = await getAxios("/system/sysDept/list")
	const res = await getAxios(
		`/system/sysUser/page?realName=&deptId=${dataId.value}&current=${current.value}&size=${pageSize.value}`
	)
	total.value = +res.total
	departmentList.value = res.records
}
list()
const close = () => {
	visibles.value = false
	empty()
}
const fabu = ref(false)
const submitForm = async formEl => {
	if (fabu.value) {
		return
	} else {
		fabu.value = true
		if (!formEl) return
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				let obj = {}
				obj.realName = form.name
				obj.nickname = form.nickname
				obj.gender = form.gender
				obj.email = form.email
				obj.deptId = form.deptId
				obj.status = form.status
				let rolesList = []
				form.role.forEach(item => {
					rolesList.push({
						id: item,
					})
				})
				obj.roleIds = form.role
				obj.roles = rolesList
				obj.phone = form.phone
				obj.officePhone = form.officePhone
				// obj.postId = form.postId
				obj.loginName = form.loginName
				if (form.password == "") {
					obj.password = ""
				} else {
					obj.password = md5(form.password)
				}
				try {
					if (title.value == "新增成员") {
						await postAxios("/system/sysUser/save", obj)
						ElMessage.success("新增成功")
					} else {
						obj.id = currentId.value
						await postAxios("/system/sysUser/edit", obj)
						ElMessage.success("编辑成功")
					}
					const res = await getAxios(
						`/system/sysUser/page?current=${current.value}&size=${pageSize.value}&deptId=${dataId.value}`
					)
					total.value = +res.total
					departmentList.value = res.records
					empty()
					visible.value = false
					// list()
				} catch (error) {
					ElMessage.error(error)
					fabu.value = false
				}
			} else {
				console.log("error submit!", fields)
				fabu.value = false
			}
		})
	}
}

const ruleFormRefs = ref()
const departmentId = ref("")
const submitForms = async formEl => {
	if (fabu.value) {
		return
	} else {
		fabu.value = true
		if (!formEl) return
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				let obj = {
					name: department.name,
					parentId: department.superior,
					remark: department.notes,
				}
				try {
					if (departmentTitle.value == "新增部门") {
						await postAxios("/system/sysDept/save", obj)
						ElMessage.success("新增成功")
						dataList.value = await getAxios("/system/sysDept/list")
						visibles.value = false
						empty()
					} else {
						obj.id = departmentId.value
						await postAxios("/system/sysDept/edit", obj)
						ElMessage.success("修改成功")
						dataList.value = await getAxios("/system/sysDept/list")
						visibles.value = false
						empty()
					}
				} catch (error) {
					ElMessage.error(error)
					fabu.value = false
				}
			} else {
				console.log("error submit!", fields)
				fabu.value = false
			}
		})
	}
}

const submitFormsKey = async formEl => {
	if (fabu.value) {
		return
	} else {
		fabu.value = true
		if (!formEl) return
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				let obj = {}
				obj.id = userId.value
				obj.password = md5(formKey.password)
				if (userInfo.value.loginName == "admin") {
					obj.loginName = formKey.loginName
					if (formKey.loginName == "") {
						ElMessage.error("登录名不能为空")
						return
					}
				}
				try {
					await postAxios(`/system/sysUser/longinNamePwd`, obj)
					ElMessage.success("修改成功")
					visiblesKey.value = false
					const res = await getAxios(
						`/system/sysUser/page?current=${current.value}&size=${pageSize.value}&deptId=${dataId.value}`
					)
					total.value = +res.total
					departmentList.value = res.records
					empty()
				} catch (error) {
					ElMessage.error(error)
					fabu.value = false
				}
			} else {
				console.log("error submit!", fields)
				fabu.value = false
			}
		})
	}
}
const takeEffect = async (row, item) => {
	const obj = row
	obj.status = item
	await postAxios("/system/sysUser/edit", obj)
}
const currentId = ref("")
//编辑
const editTable = async row => {
	fabu.value = false
	currentId.value = row.id
	part.value = await getAxios("/system/sysRole/list")
	title.value = "编辑成员"
	const res = await getAxios(`/system/sysUser/info?id=${row.id}`)
	options.value = await getAxios(`/system/sysPost/list?deptId=${res.deptId}`)
	form.name = res.realName
	form.nickname = res.nickname
	form.gender = res.gender
	form.email = res.email
	form.status = res.status
	form.deptId = res.deptId
	res.roles.forEach(item => {
		form.role.push(item.id)
	})
	form.phone = res.phone
	form.officePhone = res.officePhone
	form.loginName = res.loginName
	visible.value = true
	passwordIf.value = false
	dengUser.value = false
}
const wordClone = () => {
	visiblesKey.value = false
	empty()
}
const delTable = async row => {
	ElMessageBox.confirm("是否确认删除", "提示", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning",
	}).then(async () => {
		try {
			await postAxios(`/system/sysUser/delete?id=${row.id}`)
			list()
			ElMessage.success("删除成功")
		} catch (error) {
			ElMessage.error(error)
		}
	})
}
const closeDepartment = () => {
	visibles.value = false
	department.name = ""
	department.notes = ""
	department.superior = ""
}
const title = ref("")
//新增成员
const addUser = async () => {
	fabu.value = false
	dengUser.value = true
	form.loginName = ""
	passwordIf.value = true
	title.value = "新增成员"
	part.value = await getAxios("/system/sysRole/list")
	visible.value = true
	await nextTick()
	form.deptId = dataId.value
	ruleFormRef.value?.resetFields(form.deptId)
}
const chooseJqfl = async val => {
	if (val) {
		form.deptId = val[val.length - 1]
		options.value = await getAxios(`/system/sysPost/list?deptId=${form.deptId}`)
	}
}
const quXiao = () => {
	visible.value = false
	empty()
}

//获取部门树级菜单
const tabList = async data => {
	dataId.value = data.id
	parentId.value = data.parentId
	const obj = {
		deptId: data.id,
	}
	const res = await getAxios(`/system/sysUser/page?current=${current.value}&size=${pageSize.value}`, obj)
	total.value = +res.total
	departmentList.value = res.records
	onSearchText.value = ""
}
const selectClick = row => {
	tableLis.value = row
}
const efficacy = async val => {
	try {
		if (tableLis.value.length) {
			let listStr = []
			if (val) {
				tableLis.value.forEach(item => {
					if (item.status == 1) {
						return
					}
					listStr.push(item.id)
				})
				if (listStr.length == 0) {
					return ElMessage.error("当前为已生效")
				} else {
					await postAxios("/system/sysUser/setStatus?num=1", listStr)
				}
			} else {
				tableLis.value.forEach(item => {
					if (item.status == 2) {
						return
					}
					listStr.push(item.id)
				})
				if (listStr.length == 0) {
					return ElMessage.error("当前为未生效")
				} else {
					await postAxios("/system/sysUser/setStatus", listStr)
				}
			}
			tableLis.value = []
			const res = await getAxios(
				`/system/sysUser/page?current=${current.value}&size=${pageSize.value}&deptId=${dataId.value}`
			)
			total.value = +res.total
			departmentList.value = res.records
			ElMessage.success("操作成功")
		} else {
			ElMessage.error("请先选择用户")
		}
	} catch (error) {
		ElMessage.error(error)
	}
}
function empty() {
	form.name = ""
	form.nickname = ""
	form.gender = ""
	form.email = ""
	form.deptId = ""
	form.status = 2
	form.role = []
	form.phone = ""
	form.officePhone = ""
	// form.postId = ""
	form.loginName = ""
	form.password = ""
	department.name = ""
	department.superior = ""
	department.notes = ""
	formKey.password = ""
	formKey.loginName = ""
}
const chooseJqfls = async val => {
	department.superior = val[val.length - 1]
}
//全局搜索
const onSearch = async () => {
	if (onSearchText.value == "") {
		ElMessage.error("请输入内容进行搜索")
	} else {
		try {
			const res = await getAxios(
				`/system/sysUser/page?current=1&size=${pageSize.value}&realName=${onSearchText.value}&deptId=${dataId.value}`
			)
			total.value = +res.total
			departmentList.value = res.records
			current.value = "1"
		} catch (error) {
			ElMessage.error(error)
		}
	}
}
const fetchList = async val => {
	const res = await getAxios(
		`/system/sysUser/page?current=${current.value}&size=${pageSize.value}&deptId=${dataId.value}`
	)
	total.value = +res.total

	departmentList.value = res.records
}

const editTree = async data => {
	departmentTitle.value = "编辑部门"
	fabu.value = false
	departmentId.value = data.id
	visibles.value = !visibles.value
	const res = await getAxios(`/system/sysDept/info?id=${data.id}`)
	department.name = res.name
	department.superior = res.parentId
	department.notes = res.remark
	if (data.parentId == null) {
		ruless.superior = []
	} else {
		ruless.superior = [{ required: true, message: "请选择上级部门", trigger: "change" }]
	}
}
const delTree = async data => {
	ElMessageBox.confirm("是否确认删除", "提示", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning",
	}).then(async () => {
		try {
			await postAxios(`/system/sysDept/delete?id=${data.id}`)
			list()
			ElMessage.success("删除成功")
		} catch (error) {
			ElMessage.error(error)
		}
	})
}

const keyTable = async val => {
	userId.value = val.id
	formKey.loginName = val.loginName
	fabu.value = false
	visiblesKey.value = true
}
const resetting = async () => {
	onSearchText.value = ""
	const res = await getAxios(
		`/system/sysUser/page?current=1&size=${pageSize.value}&realName=${onSearchText.value}&deptId=${dataId.value}`
	)
	total.value = +res.total
	departmentList.value = res.records

	current.value = "1"
}
const onEnable = async (val, type) => {
	let obj = val
	obj.status = type
	try {
		await postAxios("/system/sysUser/edit", obj)
	} catch (error) {
		ElMessage.error(error)
	}
}
</script>
<style lang="scss" scoped>
@import "/style/basis";

.el-tree {
	:deep(.el-tree-node__content) {
		height: 34px;
		overflow: hidden;
		&:hover {
			.el-button {
				opacity: 1;
			}
		}
	}
	.el-tree-item {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		width: calc(100% - 30px);
	}
	.treeRefSpan {
		margin-right: auto;
		text-overflow: ellipsis;
		overflow: hidden;
		white-space: nowrap;
		flex: 1;
	}
	.el-button {
		opacity: 0;
	}
}

.zuZhiJiaGou {
	background-color: #f8f8f8;
	height: 100%;
	position: relative;
	.nav-dis {
		width: 25px;
		padding: 10px 0;
		text-align: center;
		background-color: #2972fa;
		color: #fff;
		display: none;
		position: fixed;
		top: 50;
		left: 0;
		z-index: 999;
		border-radius: 3px;
		@include maxWidth(768) {
			display: block;
		}
	}
	.input-box {
		margin-bottom: 30px;

		.search-btn {
			width: 80px;
			height: 27px;
			border-radius: 0 15px 15px 0;
			@include maxWidth(1024) {
				width: 60px;
			}
			@include maxWidth(768) {
				width: 100px;
			}
			@include maxWidth(450) {
				width: 70px;
			}
		}

		input {
			width: 150px;
			height: 27px;
			background: #f5f6f7;
			border: 1px solid #e8e8ed;
			border-radius: 15px 0 0 15px;
			padding: 0 10px;
			@include maxWidth(1024) {
				width: 120px;
			}
			@include maxWidth(768) {
				width: 200px;
			}
			@include maxWidth(450) {
				width: 120px;
			}
		}
	}

	.right {
		width: 250px;
		height: 100%;
		overflow-y: scroll;
		border-right: 1px solid #ebeef5;
		@include maxWidth(1024) {
			width: 200px;
		}

		:deep(.el-tree-node__expand-icon) {
			font-size: 14px;
		}

		:deep(.el-tree) {
			padding: 10px 0;
			color: #606266;
			font-size: 16px;
		}

		.title {
			border-bottom: 1px solid #dcdfe6;
			padding: 15px;
		}
	}

	:deep(.el-radio__input.is-checked .el-radio__inner::after) {
		background: #fff;
	}

	:deep(.cheng-dialog) {
		// width: 700px !important;
	}

	:deep(.cheng-dialog .bu-select) {
		width: 100% !important;
	}

	:deep(.bu-select .el-input__wrapper) {
		border-radius: 3px 0 0 3px !important;
	}

	:deep(.cheng-dialog .el-dialog__body) {
		padding: 20px 30px !important;
	}

	.left-bottom {
		padding: 25px;
		.tagButton {
			cursor: pointer;
		}

		.table-head2 {
			border: 1px solid #eceef5;
			height: 50px;
			padding: 0 2%;
		}

		.table-head {
			margin-bottom: 25px;

			.primary {
				width: 90px;
				height: 30px;
				border-radius: 2px;
			}

			.danger {
				width: 90px;
				height: 30px;
				border-radius: 2px;
				margin-left: 20px;
			}
		}

		:deep(.el-table) {
			border: 1px solid #eceef5;
		}

		:deep(.el-table th.el-table__cell) {
			background-color: #f4f7fa;
		}

		:deep(.el-table .el-table__cell) {
			height: 50px;
			color: #606266;
		}
	}

	.left {
		margin: 25px;
		// height: 100%;
		overflow-y: scroll;
	}
}
.pagination-class {
	display: flex;
	justify-content: center;
	margin-top: 20px;
}

.flex-item {
	display: flex;
	justify-content: space-between;
	position: relative;
	.i-item {
		position: absolute;
		right: 0;
		top: -5px;
		color: #666666 !important;
	}
}
.popover {
	font-size: 16px;
	cursor: pointer;
	.popover-item {
		padding-bottom: 5px;
	}
}
.left-bumen {
	@include maxWidth(768) {
		display: none;
	}
}
.table-color {
	:deep(.el-button) {
		&:focus {
			color: #606266;
			background-color: #fff;
			border: 1px solid #dcdfe6;
		}
	}
}

.table-head3 {
	padding-bottom: 20px;
	.primary {
		margin-left: 15px;
	}

	.box-button-top {
		@include maxWidth(445) {
			margin-top: 2vh;
		}
	}
}

.label-icon {
	margin-left: 5px;
	padding-top: 15px;
}
</style>
